package cn.newgrand.netcall.transcript;

import java.awt.Color;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;

import org.jdesktop.swingx.calendar.DateUtils;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.ui.transcript.MessageTranscriptItem;
import org.jivesoftware.spark.ui.transcript.MessageTranscriptPane;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.TaskEngine;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;

import cn.newgrand.netcall.integration.AppSysMesPlugin;
import cn.newgrand.netcall.integration.message.AppSysMessageItem;
import cn.newgrand.netcall.integration.message.MessageParser;

/**
 * 用于管理所有的历史消息操作
 * 
 * @author SidneyRen
 *
 */
public class HistoryMessageManager {

	private final String timeFormat = ((SimpleDateFormat) SimpleDateFormat
			.getDateInstance(SimpleDateFormat.SHORT)).toPattern();
	
	private final String dateFormat = ((SimpleDateFormat) SimpleDateFormat
			.getDateInstance(SimpleDateFormat.FULL)).toPattern();
	
	private final SimpleDateFormat notificationDateFormatter;
	private final SimpleDateFormat messageDateFormatter;
	private static DateFormat FORMATTER;
	private HistoryMessagePanel messageHistoryPanel;
	private static HistoryMessageManager instance;
	private final LocalPreferences pref = SettingsManager.getLocalPreferences();
	private final SimpleDateFormat messageTimeFormatter ;

	static {
		FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
	}
	
	public static HistoryMessageManager getInstance() {
		if(null==instance)	
			instance = new HistoryMessageManager();
		return instance;
	}
	
	private HistoryMessageManager() {
		//TODO
		notificationDateFormatter = new SimpleDateFormat(dateFormat);
		messageDateFormatter = new SimpleDateFormat(timeFormat);
		messageTimeFormatter= new SimpleDateFormat(pref.getTimeFormat());
	}
	
	/**
	 * 创建历史消息面板
	 * 
	 * @param title
	 * @return
	 */
	public HistoryMessagePanel getHistoryMessagePanel(String title){
		return new HistoryMessagePanel(title);
	}
		
	public void showBroadcastHistory(String filename) {
		showOnPanel(filename, null,getHistoryMessagePanel(filename));
	}

	public void showTranscript(String jid) {
		showOnPanel(jid, null,getHistoryMessagePanel(jid));
	}
	
	public void showSearchResult(String title,Date date,final HistoryMessagePanel messageHistoryPanel){
		showOnPanel(title, date, messageHistoryPanel);
	}
	
	public void showOnPanel(final String title, final Date date,final HistoryMessagePanel messageHistoryPanel) {
		
		SwingWorker transcriptLoader = new SwingWorker() {
			public Object construct() {
				//TODO 
				String bareJID = StringUtils.parseBareAddress(title);
				//获取文件名为 appsys的消息信息
				return ChatTranscripts.getChatTranscript("appsys");
			}
			
			public void finished() {
				final MessageTranscriptPane transcriptPane =  messageHistoryPanel.getTranscriptPane();
				messageHistoryPanel.setAllTitle("业务系统");
				final ChatTranscript transcript = (ChatTranscript) get();
				final List<HistoryMessage> list = transcript.getMessages();
				final String personalNickname = SparkManager.getUserManager().getNickname();
				
				final StringBuilder builder = new StringBuilder();
				
				final TimerTask transcriptTask = new TimerTask() {
					public void run() {
						Date lastPost = null;
						String lastPerson = null;
						boolean initialized = false;
						// TODO
						boolean flag = true;
						int countRow=0;
						int i = 0;
//						for(i=0;i<(list.size()>5?5:list.size());i++){
						transcriptPane.clear();
						List<HistoryMessage> tempList = new ArrayList<HistoryMessage>();
						if(list.size()>0&&null!=date){
							tempList.clear();
							for(HistoryMessage message : list){
//								System.out.println(date+"   "+message.getDate());
//								System.out.println(DateUtils.getDaysDiff(date.getTime(),message.getDate().getTime()));
								if(0==DateUtils.getDaysDiff(date.getTime(),message.getDate().getTime())){
//								date.equals(messageTimeFormatter.format(message.getDate()));
									tempList.add(message);
								}
							}
						}else {
							HistoryMessage lastMessage = list.get(list.size()-1);
							for(HistoryMessage message : list){
								if(0==DateUtils.getDaysDiff(lastMessage.getDate().getTime(),message.getDate().getTime())||1==DateUtils.getDaysDiff(lastMessage.getDate().getTime(),message.getDate().getTime())){
									tempList.add(message);
								}
							}
//							lastMessage.getDate();
//							for(i=list.size()>5?list.size()-5:0;i<list.size();i++){
//								tempList.add( list.get(i));
//							}
						}
						
						for (HistoryMessage message : tempList) {
							countRow=countRow++;
							String value = "["+ messageTimeFormatter.format(message.getDate()) + "] ";
							// TODO判断
							String color = "blue";
							String from = message.getFrom();
							String nickname = SparkManager.getUserManager()
							.getUserNicknameFromJID(
									message.getFrom());
							String body = org.jivesoftware.spark.util.StringUtils
							.escapeHTMLTags(message.getBody());
							if (nickname.equals(message.getFrom())) {
								String otherJID = StringUtils
								.parseBareAddress(message.getFrom());
								String myJID = SparkManager.getSessionManager().getBareAddress();
								
								if (otherJID.equals(myJID)) {
									nickname = personalNickname;
								} else {
									nickname = StringUtils
									.parseName(nickname);
								}
								
							}
							//判断 对话人
							if (!StringUtils.parseBareAddress(from).equals(
									SparkManager.getSessionManager()
									.getBareAddress())) {
								color = "red";
							}
							
							long lastPostTime = lastPost != null ? lastPost
									.getTime() : 0;
									int diff = DateUtils.getDaysDiff(lastPostTime,
											message.getDate().getTime());
//								System.out.println("b"+diff);
//								System.out.println(message.getDate());
									if (diff != 0) {
										//注意transcriptPane重写了插入自定义 文字方法
										transcriptPane.insertCustomText(notificationDateFormatter.format(message.getDate()), true, false, new Color(0, 0, 255));
										if (initialized) {
											builder.append("<tr><td><br></td></tr>");
										}
										
										builder
										.append(
												"<tr><td colspan=2><font size=4 color=gray><b><u>")
												.append(
														notificationDateFormatter.format(message.getDate()))
														.append("</u></b></font></td></tr>");
										lastPerson = null;
										initialized = true;
									}
									
//								transcriptPane.addComponent(new TranscriptItem(nickname, body, value));
									
									// value
									
									boolean newInsertions = lastPerson == null
									|| !lastPerson.equals(nickname);
									
									if (newInsertions) {
										builder
										.append("<tr valign=top><td colspan=2 nowrap>");
										builder.append("<font size=4 color='")
										.append(color).append("'><b>");
										builder.append(nickname);
										builder.append("</b></font>");
										builder.append("</td></tr>");
									}
									
									builder
									.append("<tr valign=top><td align=left nowrap>");
									
									builder.append(value);
									
									builder.append("</td><td align=left>");
									builder.append(org.jivesoftware.spark.util.StringUtils.unescapeFromXML(body));
									
									builder.append("</td></tr>");
									
									lastPost = message.getDate();
									lastPerson = nickname;
									transcriptPane.addComponent(new MessageTranscriptItem("i6系统消息", org.jivesoftware.spark.util.StringUtils.unescapeFromXML(body), value));
									
						}
						
						builder.append("</table></body></html>");
						messageHistoryPanel.scrollToBottom();
						// Handle no history
						if (tempList.size() == 0) {
							transcriptPane.insertCustomText("没有记录", true, false, new Color(0, 0, 255));
						}
						
//						window.setText(builder.toString());
						//
						builder.replace(0, builder.length(), "");
					}
				};
				
				TaskEngine.getInstance().schedule(transcriptTask, 10);
			}
		};
		transcriptLoader.start();
		
	}
	
	public void showAppHistory(ChatTranscript transcript) {
		showAppMessage(transcript, null,getHistoryMessagePanel(AppSysMesPlugin.APP_SYS_MES_FILE_NAME));
	}
	
	
	public void showAppMessage(final ChatTranscript transcript, final Date date,final HistoryMessagePanel messageHistoryPanel) {
		
		SwingWorker transcriptLoader = new SwingWorker() {
			public Object construct() {
				//TODO 
//				String bareJID = StringUtils.parseBareAddress(title);
				//获取文件名为 appsys的消息信息
//				return ChatTranscripts.getChatTranscript("appsys");
				return true;
			}

			public void finished() {
				final MessageTranscriptPane transcriptPane =  messageHistoryPanel.getTranscriptPane();
				messageHistoryPanel.setAllTitle("业务系统");
//				final ChatTranscript transcript = (ChatTranscript) get();
				final List<HistoryMessage> list;
				if(null==transcript){
					list = new ArrayList<HistoryMessage>();
				}else{
					list = transcript.getMessages();
				}
				
				final String personalNickname = SparkManager.getUserManager().getNickname();

				final StringBuilder builder = new StringBuilder();

				final TimerTask transcriptTask = new TimerTask() {
					public void run() {
						Date lastPost = null;
						String lastPerson = null;
						boolean initialized = false;
						// TODO
						boolean flag = true;
						int countRow=0;
						int i = 0;
//						for(i=0;i<(list.size()>5?5:list.size());i++){
						transcriptPane.clear();
						List<HistoryMessage> tempList = new ArrayList<HistoryMessage>();
						if(list.size()>0&&null!=date){
							tempList.clear();
							for(HistoryMessage message : list){
//								System.out.println(date+"   "+message.getDate());
//								System.out.println(DateUtils.getDaysDiff(date.getTime(),message.getDate().getTime()));
								if(0==DateUtils.getDaysDiff(date.getTime(),message.getDate().getTime())){
//								date.equals(messageTimeFormatter.format(message.getDate()));
								tempList.add(message);
								}
							}
						}else {
							HistoryMessage lastMessage = list.get(list.size()-1);
							for(HistoryMessage message : list){
								if(0==DateUtils.getDaysDiff(lastMessage.getDate().getTime(),message.getDate().getTime())||1==DateUtils.getDaysDiff(lastMessage.getDate().getTime(),message.getDate().getTime())){
									tempList.add(message);
								}
							}
//							lastMessage.getDate();
//							for(i=list.size()>5?list.size()-5:0;i<list.size();i++){
//								tempList.add( list.get(i));
//							}
						}
						
						for (HistoryMessage message : tempList) {
							countRow=countRow++;
							String value = "["+ messageTimeFormatter.format(message.getDate()) + "] ";
							// TODO判断
								String color = "blue";
								String from = message.getFrom();
								String nickname = SparkManager.getUserManager()
										.getUserNicknameFromJID(
												message.getFrom());
								String body = org.jivesoftware.spark.util.StringUtils
										.escapeHTMLTags(message.getBody());
								if (nickname.equals(message.getFrom())) {
									String otherJID = StringUtils
											.parseBareAddress(message.getFrom());
									String myJID = SparkManager.getSessionManager().getBareAddress();

									if (otherJID.equals(myJID)) {
										nickname = personalNickname;
									} else {
										nickname = StringUtils
												.parseName(nickname);
									}
									
								}
								//判断 对话人
								if (!StringUtils.parseBareAddress(from).equals(
										SparkManager.getSessionManager()
												.getBareAddress())) {
									color = "red";
								}

								long lastPostTime = lastPost != null ? lastPost
										.getTime() : 0;
								int diff = DateUtils.getDaysDiff(lastPostTime,
										message.getDate().getTime());
//								System.out.println("b"+diff);
//								System.out.println(message.getDate());
								if (diff != 0) {
									//注意transcriptPane重写了插入自定义 文字方法
									transcriptPane.insertCustomText(notificationDateFormatter.format(message.getDate()), true, false, new Color(50,108,189));
									if (initialized) {
										builder.append("<tr><td><br></td></tr>");
									}

									builder
											.append(
													"<tr><td colspan=2><font size=4 color=gray><b><u>")
											.append(
													notificationDateFormatter.format(message.getDate()))
											.append("</u></b></font></td></tr>");
									lastPerson = null;
									initialized = true;
								}
								
//								transcriptPane.addComponent(new TranscriptItem(nickname, body, value));

								// value

								boolean newInsertions = lastPerson == null
										|| !lastPerson.equals(nickname);

								final String tempBody = org.jivesoftware.spark.util.StringUtils.unescapeFromXML(body);
								final MessageParser mp = new MessageParser(tempBody);
								if (newInsertions) {
									builder
											.append("<tr valign=top><td colspan=2 nowrap>");
									builder.append("<font size=4 color='")
											.append(color).append("'><b>");
									builder.append(nickname);
									builder.append("</b></font>");
									builder.append("</td></tr>");
								}

								builder
										.append("<tr valign=top><td align=left nowrap>");

								builder.append(value);

								builder.append("</td><td align=left>");
								builder.append(tempBody);

								builder.append("</td></tr>");
								
								lastPost = message.getDate();
								lastPerson = nickname;
//								MessageParser mp = new MessageParser(bodyXML);
								transcriptPane.addComponent(new AppSysMessageItem("",tempBody, "", mp.getContentWithCount()));
//								transcriptPane.addComponent(new AppSysMessageItem("业务消息",tempBody, value, mp.getContentWithCount()));

						}
						
						builder.append("</table></body></html>");
						messageHistoryPanel.scrollToBottom();
						// Handle no history
						if (tempList.size() == 0) {
							transcriptPane.insertCustomText("没有记录", true, false, new Color(0, 0, 255));
						}

//						window.setText(builder.toString());
						//
						builder.replace(0, builder.length(), "");
					}
				};

				TaskEngine.getInstance().schedule(transcriptTask, 10);
			}
		};
		transcriptLoader.start();

	}
	

}
